﻿using ImoviesBlazorAntPro.Server.Helpers;
using ImoviesBlazorAntPro.Server.Repository;
using ImoviesBlazorAntPro.Shared.Utils;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ImoviesBlazorAntPro.Server.Controllers
{
    /// <summary>
    /// 视频播放地址解析控制器
    /// </summary>
    [ApiController]
    [Route("api/playlink")]
    public class RealPlayerUrlParseController : ControllerBase
    {
        private IPlaylinkRepository _playlinkRepository;

        public RealPlayerUrlParseController(IPlaylinkRepository playlinkRepository)
        {
            this._playlinkRepository = playlinkRepository;
        }

        /// <summary>
        /// 解析真实视频播放地址
        /// </summary>
        /// <param name="linkParseReq">请求解析的参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> ParsePlaylink([FromBody] LinkParseReqParameter linkParseReq)
        {
            // 首先从缓存中查询
            var cacheRealUrl = CacheUtils.GetData<string>(linkParseReq.OriginUrl);
            if (!string.IsNullOrEmpty(cacheRealUrl))
            {
                return Ok(cacheRealUrl);
            }
            // 缓存中没有从数据库中查询
            var dbRealUrl = _playlinkRepository.GetRealUrl(linkParseReq.Vcate, linkParseReq.OriginUrl);
            if (!string.IsNullOrEmpty(dbRealUrl))
            {
                return Ok(dbRealUrl);
            }

            var htmlStr = await HtmlUtils.GetHtmlTxt(linkParseReq.OriginUrl);
            if (string.IsNullOrEmpty(htmlStr))
            {
                return Ok("");
            }
            var match = Regex.Match(htmlStr, @"},""url"":""(.*?)"",""url_next"":");
            string temp = match?.Groups[1].Value;
            if (string.IsNullOrEmpty(temp))
            {
                return Ok("");
            }
            string uri = System.Net.WebUtility.UrlDecode(temp);
            var realUrl = $"https://www.freeok.vip/okplayer/?url={uri}";

            // 更新数据库，保存真实地址
            await Task.Run(() => _playlinkRepository.UpdateLinkInfo(linkParseReq.Vcate, linkParseReq.OriginUrl, realUrl));

            // 设置缓存
            CacheUtils.SetData<string>(linkParseReq.OriginUrl, realUrl);
            return Ok(realUrl);
        }
    }
}
